const tbody = document.querySelector("tbody"); //渲染页面
const total = document.querySelector(".total"); //渲染页面的人数
// 获取学生列表
async function getStudents() {
  const res = await axios({ url: "/students" });
  // console.log(res.data);
  const students = res.data.reduce(
    (
      a,
      {
        id,
        name,
        age,
        gender,
        group,
        hope_salary,
        salary,
        province,
        city,
        area,
      }
    ) =>
      a +
      `<tr>
                      <td>${name}</td>
                      <td>${age}</td>
                      <td>${gender === 0 ? "男" : "女"}</td>
                      <td>${group}</td>
                      <td>${hope_salary}</td>
                      <td>${salary}</td>
                      <td>${province + city + area}</td>
                      <td>
                        <a href="javascript:;"  class="text-success mr-3"><i class="bi bi-pen" data-id='${id}'></i></a>
                        <a href="javascript:;" class="text-danger"><i class="bi bi-trash"  data-id='${id}'></i></a>
                      </td>
                    </tr>`,
    ""
  );
  tbody.innerHTML = students;
  total.innerText = res.data.length;
}
getStudents();

// 获取省市县
const province1 = document.querySelector('[name="province"]'); //省
const city1 = document.querySelector('[name="city"]'); //城市
const area1 = document.querySelector('[name="area"]'); //地区
//  显示省
async function getShengShiXian() {
  const res = await axios({ url: "api/province" });
  const province = res.data.reduce(
    (a, b) => a + ` <option value="${b}">${b}</option>`,
    ""
  );
  province1.innerHTML = `<option value="">--省--</option>` + province;
}
// 显示城市
province1.addEventListener("change", async function (e) {
  const cityRes = await axios({
    url: "api/city",
    params: { pname: province1.value },
  });
  const city = cityRes.data.reduce(
    (a, b) => a + ` <option value="${b}">${b}</option>`,
    ""
  );
  city1.innerHTML = `<option value="">--城市--</option>` + city;
});
// 显示地区
city1.addEventListener("change", async function (e) {
  const areaRes = await axios({
    url: "api/area",
    params: { pname: province1.value, cname: city1.value },
  });
  const area = areaRes.data.reduce(
    (a, b) => a + ` <option value="${b}">${b}</option>`,
    ""
  );
  area1.innerHTML = `<option value="">--地区--</option>` + area;
});
getShengShiXian();

// 添加学生
const formList = document.querySelector("#form");
// 添加点击事件 显示模态框
const openModal = document.querySelector("#openModal"); //点击显示模态框
const modal = new bootstrap.Modal("#modal");
openModal.addEventListener("click", function (e) {
  modalTitle.innerHTML = "添加学员";
  modal.show();
  formList.reset();
});
// 需要手动进行清空列表  上面formList.reset不能清除下拉列表
formList.addEventListener("reset", function (e) {
  city1.innerHTML = `<option value="">--城市--</option>`;
  area1.innerHTML = `<option value="">--地区--</option>`;
});
// 点击按钮 ，新增列表
formList.addEventListener("submit", async function (e) {
  e.preventDefault();
   
  const data = serialize(formList, { hash: true, empty: true });
  const  id  = data.id
  delete data.id
  for (const key in data) {
    if (!data[key]) {
      toast.show('请输入内容')
      return;
    }
  }
  // 转数字类型
  data.age = +data.age;
  data.gender = +data.gender;
  data.salary = +data.salary;
  data.hope_salary = +data.hope_salary;
  data.group = +data.group;

  let url = ''
  let method = ''
  if (modalTitle.innerText==='添加学员') {
    url= '/students';
    method='post'
  } else {
       url = `/students/${id}`
    method = "put"
  }

  await axios({ url, method, data });

  getStudents();
  modal.hide();

  toast("操作成功");
});

const modalTitle = document.querySelector(".modal-title");
// 编辑列表  和  删除
tbody.addEventListener("click", async function (e) {
  // 编辑学员
  if (e.target.classList.contains("bi-pen")) {
    const { id } = e.target.dataset;
    const res = await axios({ url: `students/${id}`});
    modalTitle.innerHTML = "编辑学员";
    modal.show();
    document.querySelector(`[name="gender"][value="${res.data.gender}"]`).checked = true;

    //   需要进行重新获取城市信息，方便下面遍历
    const cityRes = await axios({
      url: "api/city",
      params: { pname: res.data.province },
    });
    const city = cityRes.data.reduce(
      (a, b) => a + ` <option value="${b}">${b}</option>`, "");
    city1.innerHTML = `<option value="">--城市--</option>` + city;

    //   需要进行重新获取地区信息，方便下面遍历
    const areaRes = await axios({
      url: "api/area",
      params: { pname: res.data.province, cname: res.data.city },
    });
    const area = areaRes.data.reduce((a, b) => a + ` <option value="${b}">${b}</option>`,"");
    area1.innerHTML = `<option value="">--地区--</option>` + area;

    //    找到所有form里面带有 name  属性
    const names = form.querySelectorAll("[name]");
    console.log(names);
    //用所有names变量 进行遍历
    names.forEach((item) => {
      // 这里要进行一个判断 因为 性别 已经在上面写好了，所以这里不需要在进行遍历，不然会报错
      if (item.name !== "gender") {
        //   除了性别遍历所有包含name属性进行回显
        item.value = res.data[item.name];
      }
    });
  }else
  // 删除学员  利用事件委托
  if (e.target.classList.contains('bi-trash')) {
    const id = e.target.dataset.id
    // 给出提示 判断是否删除
    if (!confirm('您确定要删除吗？')) {
      return
    }
   const res =  await axios({ url: `/students/${id}`, method: 'DELETE'})
    console.log(res);
    getStudents();
    toast.show('删除成功')
  }


});


